const XLSX = require('xlsx')
const path = require('path')
const fs = require('fs')

const getXlSXData = url => {
  const workbook = XLSX.readFile(url)
  const sheetNames = workbook.SheetNames // 获取工作表名称
  const sheet = workbook.Sheets[sheetNames[0]]
  const data = XLSX.utils.sheet_to_json(sheet) // 将工作表转换为JSON对象
  return data
}

const writeOutXlSXData = (data, name = 'output') => {
  // 创建一个新的excel工作簿
  const workbook = XLSX.utils.book_new()

  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet(data)

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 写文件到磁盘
  XLSX.writeFile(workbook, `result/${name}.xlsx`)
}
// 写出数据到Excel文件data 格式
// const data = [
//   ['A1', 'B1', 'C1'], // 表头
//   [1, 2, 3], // 数据行1
//   [4, 5, 6], // 数据行2
// ]
// 获取文件夹下所有文件
const getFilesRecursively = dir => {
  const files = fs.readdirSync(dir)
  let fileList = []

  files.forEach(file => {
    const filePath = path.join(dir, file)
    const stat = fs.statSync(filePath)

    if (stat.isDirectory()) {
      // 递归获取子文件夹中的文件
      fileList = fileList.concat(getFilesRecursively(filePath))
    } else {
      fileList.push(filePath)
    }
  })

  return fileList
}

const getData = url => {
  const files = getFilesRecursively(url)
  const sumData = files.reduce((sum, item) => {
    sum.push(...getXlSXData(item))
    return sum
  }, [])
  return sumData
}
const getWireFile = (sourceData, customData, name = 'i18n') => {
  let result = [['source', 'target', 'fuzzy', 'context']]
  const mapData = customData.map(item => item.context)
  sourceData.forEach((item, index) => {
    if (!mapData.includes(item.context)) {
      result[index + 1] = [item.source, item.target, 'False', item.context]
    }
  })
  const filterResult = result.filter(v => !!v[0])
  writeOutXlSXData(filterResult, name)
}

const sourceData = getData('./source')
const customData = getData('./custom')
getWireFile(sourceData, customData)
